<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center;background-color: rgba(117, 215, 156,0.9)">
    <div style="display: flex; background-color: white; width: 50%; border-radius: 8px; overflow: hidden">
      <!--flex: 1 把div分成两半，一边一半-->
      <div style="flex: 1">
        <img src="@/assets/images/shanLogin2.png" alt="" style="width: 100%">
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center;">
        <el-form :model="user" :rules="rules" ref="loginRef" style="width: 80%;"> <!-- 绑定user对象 -->
          <div style="font-size: 20px; font-weight: bold;text-align: center; margin-bottom: 30px">欢迎来到闪闪充电后台管理
          </div>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" placeholder="请输入账号" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="user.password"  show-password @keyup.enter.native="handleEnterKey" ></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div style="display: flex">
              <el-input style="flex: 1" prefix-icon="el-icon-circle-check" placeholder="验证码"
                        v-model="user.code"></el-input>
              <div style="flex: 1; height: 40px">
                <ValidCode @update:value="getCode"/>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%; background-color: #06b54c" @click="login">登 录</el-button>
          </el-form-item>
          <div style="display: flex">
            <div style="flex: 1">还没有账号？<span style="color: #0f9876; cursor: pointer"
                                                  @click="$router.push('/register')">点击注册</span></div>
            <div style="flex: 1; text-align: right"><span style="color: #0f9876; cursor: pointer" @click="handleForgetPass">忘记密码</span></div>
          </div>
        </el-form>

      </div>
    </div>
    <el-dialog title="忘记密码" :visible.sync="forgetPassDialogVis" width="30%">
      <el-form :model="forgetUserForm" label-width="80px" style="padding-right: 20px">
        <el-form-item label="用户名">
          <el-input prefix-icon="el-icon-user" placeholder="请输入用户名" v-model="forgetUserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input prefix-icon="el-icon-lock" placeholder="请输入手机号" v-model="forgetUserForm.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="forgetPassDialogVis = false">取 消</el-button>
        <el-button type="primary" @click="resetPassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ValidCode from "@/components/ValidCode"; // 验证码模块

export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    // 验证码校验 // toLowerCase() 转换为小写
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.toLowerCase() !== this.code) {
        callback(new Error('验证码错误'))
      } else {
        callback();
      }
    }

    return {
      code: '', // 验证码组件传过来的code
      forgetPassDialogVis: false, // 对话框默认关闭
      forgetUserForm: {}, // 存储忘记密码输入的数据
      user: {
        username: 'admin',
        password: 'admin',
        code: '',  // 表单里用户输入的code
      },
      rules: {
        username: {required: true, message: '请输入用户名', trigger: 'blur'},
        password: {required: true, message: '请输入密码', trigger: 'blur'},
        code: {validator: validateCode, trigger: 'blur'},
      }
    }
  },
  mounted() {
    // 绑定enter事件
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  methods: {
    // 监听回车登录
    handleEnterKey(event) {
      const componentName = this.$options.name;
      if (componentName == "Login") {
        const code = event.keyCode
            ? event.keyCode
            : event.which
                ? event.which
                : event.charCode;
        if (code == 13) {
          this.login();
        }
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener("keyup", this.handleEnterKey);
    },
    enterKeyup() {
      document.addEventListener("keyup", this.handleEnterKey);
    },
    // 初始化忘记密码的表单
    handleForgetPass(){
      this.forgetUserForm = {}
      this.forgetPassDialogVis = true
    },
    resetPassword(){
      this.$request.post('/password',this.forgetUserForm).then(res => {
        if (res.code === '200'){
          this.$message.success("密码重置成功，初始化为“123”")
          this.forgetPassDialogVis =false
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    // 把验证码工具生成的验证码赋值给code
    // toLowerCase() 转换为小写
    getCode(code) {
      this.code = code.toLowerCase();
    },
    login() {
      this.$refs['loginRef'].validate((valid) => {
        if (valid) {
          // 验证通过
          // 通过login接口，发送数据 this.user 得到数据 res
          this.$request.post("/login", this.user).then(res => {
            if (res.code == '200') {
              this.$router.push('/')
              this.$message.success("登录成功")
              // 存储登录成功的用户数据
              localStorage.setItem("power-user", JSON.stringify(res.data))
            } else {
              this.$message.error(res.msg)
            }

          })
        }
      })
    }
  }
}
</script>

<style scoped>
/*样式穿透*/
.el-input >>> .el-input__inner {
  height: 40px !important;
  line-height: 40px !important;
}
</style>